package jwcb.hire.common.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import jwcb.hire.common.core.utils.ThreadLocalUtil;
import jwcb.hire.common.domain.constants.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler { ;

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictInsertFill(metaObject,"createBy",Long.class, userId);
        this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
        this.strictInsertFill(metaObject,"updateBy",Long.class,userId);
        this.strictInsertFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictInsertFill(metaObject,"updateBy",Long.class,userId);
        this.strictInsertFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
    }

    /**
     * 从ThreadLocal里面获取userId
     * @return userId
     */
    private Long getUserId() {
        return ThreadLocalUtil.get(SecurityConstants.USER_ID,Long.class);
    }
}
